<?php

namespace magein\utils;

use Exception;

class File
{
    /**
     * 获取深层次的文件
     * @param $directory
     * @param array $ext
     * @param array $files
     * @return Result
     */
    public static function getTreeList($directory, array $ext = [], array &$files = []): Result
    {
        if (!is_dir($directory)) {
            return Result::error($directory . ' not a directory');
        }
        $lists = glob($directory . '/*');

        if ($lists) {
            foreach ($lists as $list) {
                if (is_file($list)) {
                    if ($ext && !in_array(pathinfo($list, PATHINFO_EXTENSION), $ext)) {
                        continue;
                    }
                    $files[] = $list;
                } elseif (is_dir($list)) {
                    self::getTreeList($list, $ext, $files);
                }
            }
        }

        return Result::success($files);
    }

    /**
     * ck = create and check
     * @throws Exception
     */
    public static function ckDir(...$_)
    {
        $dir = array_reduce($_, function ($dir, $item) {
            return $dir . trim($item, '/') . '/';
        });

        if (!is_dir($dir) && !mkdir($dir, 0777, true)) {
            throw new Exception('Failed to create directory:' . $dir);
        }

        if (!is_writeable($dir)) {
            throw new Exception('The target directory is not writable:' . $dir);
        }

        return $dir;
    }
}